package com.example.materialdesign1;

import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LoginActivity extends AppCompatActivity {
    private TextInputLayout tl_username;
    private TextInputLayout tl_password;
    private EditText username;
    private EditText password;
    private Button button;
    private static final String EMAIL_PATTERN = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
    private Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    private Matcher matcher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });
    }

    private void login() {
        String name = username.getText().toString();
        String word = password.getText().toString();
        if(!validateUserName(name)){
            tl_username.setErrorEnabled(true);
            tl_username.setError("请输入正确的邮箱地址");
        }else{
            tl_username.setErrorEnabled(false);
        }
        if(!validatePassword(word)){
            tl_password.setErrorEnabled(true);
            tl_password.setError("密码字数过少");
        }else{
            tl_password.setErrorEnabled(false);
        }
        if(validateUserName(name) && validatePassword(word)){
            tl_username.setErrorEnabled(false);
            tl_password.setErrorEnabled(false);
            Toast.makeText(LoginActivity.this,"登陆成功",Toast.LENGTH_SHORT).show();
        }
    }

    private void initView() {
        tl_username = findViewById(R.id.tl_username);
        tl_password = findViewById(R.id.tl_password);
        username = findViewById(R.id.et_username);
        password = findViewById(R.id.et_password);
        button = findViewById(R.id.bt_login);
    }
    private boolean validatePassword(String password){
        return password.length() > 6;
    }
    private boolean validateUserName(String username){
        matcher = pattern.matcher(username);
        return matcher.matches();
    }
}
